﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SCS.DAL;
using SCS.Common.Models;
using SCS.Common;
namespace SCS.Business
{
    public class MembershipRoleServices
    {
        IUnitOfWork _unitOfWork;
        public MembershipRoleServices()
        {
            _unitOfWork = new UnitOfWork();
        }

        /// <summary>
        /// Get all roles in the system
        /// </summary>
        /// <returns>role list</returns>
        public IList<MembershipRole> AllRoles()
        {
            return _unitOfWork.MembershipRole.GetAll().ToList();
        }

        /// <summary>
        /// Get role by name
        /// </summary>
        /// <param name="rolename">string</param>
        /// <returns>role</returns>
        public MembershipRole GetRole(string rolename)
        {
            return _unitOfWork.MembershipRole.Get(m => m.roleName == rolename).FirstOrDefault();
        }

        /// <summary>
        /// Get role by Id
        /// </summary>
        /// <param name="Id">ID</param>
        /// <returns>role</returns>
        public MembershipRole GetRole(int Id)
        {
            return _unitOfWork.MembershipRole.Get(m => m.roleID == Id).FirstOrDefault();

        }

        /// <summary>
        /// Create a new role
        /// </summary>
        /// <param name="role">role</param>
        public void CreateRole(MembershipRole role)
        {
            role.roleName = StringUtils.SafePlainText(role.roleName);
            _unitOfWork.MembershipRole.Add(role);
            _unitOfWork.Commit();
        }

        /// <summary>
        /// Delete a role
        /// </summary>
        /// <param name="role">role</param>
        public void Delete(MembershipRole role)
        {
            // Check if anyone else if using this role
            var okToDelete = role.MembershipUsers.Count == 0;

            if (okToDelete)
            {
                // Get any categorypermissionforoles and delete these first
                MembershipRole rolesToDelete = _unitOfWork.MembershipRole.Get(m => m.roleID == role.roleID).FirstOrDefault();

                _unitOfWork.MembershipRole.Delete(rolesToDelete);
                _unitOfWork.Commit();
            }
            else
            {
                //Error
            }
        }

        /// <summary>
        /// Save a role
        /// </summary>
        /// <param name="role">role</param>
        public void Save(MembershipRole role)
        {
            role.roleName = StringUtils.SafePlainText(role.roleName);
            _unitOfWork.MembershipRole.Update(role);
            _unitOfWork.Commit();
        }

    }
}
